package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LoopABC
{

    public static void main(String[] args)
    {
        Loop loop = new Loop();
        new Thread(()->{
            for (int i = 0; i < 20; i++)
            {
                try
                {
                    loop.loopA();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++)
            {
                try
                {
                    loop.loopB();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++)
            {
                try
                {
                    loop.loopC();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}

class Loop
{
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private static int i = 3;
    public void loopA() throws InterruptedException
    {
        lock.lock();
        try
        {
            if (i != 3)
            {
                condition1.await();
            }
            System.out.println("A");
            condition2.signal();
            i=2;
        }
        finally
        {
            lock.unlock();
        }
    }

    public void loopB() throws InterruptedException
    {
        lock.lock();
        try
        {
            if (i != 2)
            {
                condition2.await();
            }
            System.out.println("B");
            condition3.signal();
            i=1;
        }
        finally
        {
            lock.unlock();
        }
    }

    public void loopC() throws InterruptedException
    {
        lock.lock();
        try
        {
            if (i != 1)
            {
                condition3.await();
            }
            System.out.println("C");
            condition1.signal();
            i = 3;
        }
        finally
        {
            lock.unlock();
        }
    }
}

